unit UtilsParentProcess;

interface

uses
  Windows,
  win.thread,
  win.process;
              
  procedure CreateParentProcessMonitorThread(ACoreProcess: PCoreProcess);

implementation

uses      
  //UtilsLog,
  BaseApp,
  windef_msg,
  BaseWinApp;
           
{$IFNDEF RELEASE}  
const
  LOGTAG = 'UtilsParentProcess.pas';
{$ENDIF}
  
var
  ParentProcessMonitorThread: TSysWinThread = (
    core: (threadhandle: 0; threadid: 0)
  );

function CheckParentProcessThreadProc(AParentProcess: PCoreProcess): DWORD; stdcall;
begin
  Result := 0;   
  Sleep(500);
  //Log(LOGTAG, 'CheckParentProcessThreadProc');
  while True do
  begin
    Sleep(500);     
    if not IsWindow(AParentProcess.AppCmdWnd) then
    begin
      Break;
    end;
  end;
  //Log(LOGTAG, 'CheckParentProcessThreadProc End');
  if nil <> GlobalBaseWinApp then
  begin                    
    //Log(LOGTAG, 'CheckParentProcessThreadProc Terminate App');
    GlobalBaseWinApp.RunStatus := RunStatus_RequestShutdown;
    Sleep(1000);
    if IsWindow(GlobalBaseWinApp.AppWindow) then
    begin                                        
      //Log(LOGTAG, 'CheckParentProcessThreadProc Terminate App Post Request');
      PostMessage(GlobalBaseWinApp.AppWindow, WM_AppRequestEnd, 0, 0);
    end;
    //GlobalBaseApp.Terminate;
  end;        
  //Log(LOGTAG, 'CheckParentProcessThreadProc Exit');
  ExitThread(0);
end;

procedure CreateParentProcessMonitorThread(ACoreProcess: PCoreProcess);
var
  tmpExitCode: DWORD;
begin             
  //Log(LOGTAG, 'CreateParentProcessMonitorThread');
  if (0 <> ParentProcessMonitorThread.Core.ThreadHandle) and
     (INVALID_HANDLE_VALUE <> ParentProcessMonitorThread.Core.ThreadHandle) then
  begin
    Windows.GetExitCodeThread(ParentProcessMonitorThread.Core.ThreadHandle, tmpExitCode);
    if Windows.STILL_ACTIVE = tmpExitCode then
    begin
      exit;
    end;
  end;   
  ParentProcessMonitorThread.Core.ThreadHandle :=
        Windows.CreateThread(nil, 0, @CheckParentProcessThreadProc, ACoreProcess, CREATE_SUSPENDED,
        ParentProcessMonitorThread.Core.ThreadId);
  ResumeThread(ParentProcessMonitorThread.Core.ThreadHandle);
end;
    
end.
